package com.kyxx.topics.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kyxx.topics.BaseActivity;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.bean.EditMemberCardBean;
import com.kyxx.topics.bean.MembershipCardBean;
import com.kyxx.topics.net.LoadingStringCallBack;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.StringUtil;
import com.kyxx.topics.utils.ToastUtils;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.wevey.selector.dialog.DialogOnClickListener;
import com.wevey.selector.dialog.NormalAlertDialog;

import org.json.JSONException;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class EditMemberActivity extends BaseActivity {
    @Bind(R.id.iv_back)
    ImageView iv_back;
    @Bind(R.id.tv_edit)
    TextView tv_edit;
    @Bind(R.id.rl_edit_bar)
    RelativeLayout rl_edit_bar;
    @Bind(R.id.iv_edit_card_icon)
    ImageView iv_edit_card_icon;
    @Bind(R.id.rl_edit_card_icon)
    RelativeLayout rl_edit_card_icon;
    @Bind(R.id.tv_edit_member_num)
    TextView tv_edit_member_num;
    @Bind(R.id.tv_edit_member_name)
    TextView tv_edit_member_name;
    @Bind(R.id.tv_edit_member_mobile)
    TextView tv_edit_member_mobile;
    @Bind(R.id.tv_edit_member_other_msg)
    TextView tv_edit_member_other_msg;
    @Bind(R.id.tv_edit_member_delete)
    TextView tv_edit_member_delete;
    @Bind(R.id.tv_member_icon)
    TextView tv_member_icon;
    @Bind(R.id.rl_edit_member_scan)
    RelativeLayout rl_edit_member_scan;
    @Bind(R.id.fl)
    FrameLayout fl;
    private MembershipCardBean bean;
    private EditMemberCardBean cardBean;
    public static final int NUM = 1;
    public static final int NAME = 2;
    public static final int MOBILE = 3;
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions option;
    private  NormalAlertDialog dialog;
    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_edit_member);
        ButterKnife.bind(this);
        bean = (MembershipCardBean) getIntent().getSerializableExtra("shipBean");
        option = new DisplayImageOptions.Builder()
                // 设置图片在下载期间显示的图片
                .showImageOnLoading(R.mipmap.image_default)
                // 设置图片Uri为空或是错误的时候显示的图片
                .showImageForEmptyUri(R.mipmap.image_default)
                // 设置图片加载/解码过程中错误时候显示的图片
                .showImageOnFail(R.mipmap.image_default)
                .cacheInMemory(true)
                // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)
                // 设置下载的图片是否缓存在SD卡中
                .bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型
                // .displayer(new RoundedBitmapDisplayer(9999))
                .resetViewBeforeLoading(false)
                .build();
    }

    @Override
    protected void findViewById() {

    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void processLogic() {
        getCardInfo();
        if (bean.getShop_color() == null || bean.getShop_color().contains(",")) {
            bean.setShop_color("FFFDBB2B");
        } else {
            bean.setShop_color("FF" + bean.getShop_color());
        }
        int a = new java.math.BigInteger("ffffff", 16).intValue();
        int b = new java.math.BigInteger(bean.getShop_color(), 16).intValue();
        rl_edit_bar.setBackgroundColor(b);
        rl_edit_card_icon.setBackgroundColor(b);
        if(!StringUtil.isEmpty(bean.getType_logo())){
            imageLoader.displayImage(UrlUtils.BASEHTTP + bean.getType_logo(),iv_edit_card_icon, options);
            fl.setVisibility(View.GONE);
            iv_edit_card_icon.setVisibility(View.VISIBLE);
        }else {
            fl.setVisibility(View.VISIBLE);
            tv_member_icon.setText(bean.getType_name().substring(0,1));
            iv_edit_card_icon.setVisibility(View.GONE);
            if(a == b){
                tv_member_icon.setTextColor(getResources().getColor(R.color.black));
            }else{
                tv_member_icon.setTextColor(getResources().getColor(R.color.white));
            }
        }

        tv_edit_member_num.setText(bean.getCardnum());
        tv_edit_member_mobile.setText(bean.getMobile());
    }

    private void getCardInfo() {
        HttpParams params = new HttpParams();
        JSONObject obj = new JSONObject();
        obj.put("uid", BaseApp.getModel().getId());
        obj.put("type_id", bean.getType_id());
        params.put("json", obj.toString());
        OkGoRequest.post(UrlUtils.VIP_CARD_MEMBRT_INFO, context, "vip_item" , CacheMode.NO_CACHE, params, new LoadingStringCallBack(EditMemberActivity.this,true) {
            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    org.json.JSONObject result = new org.json.JSONObject(s);
                    cardBean = JSONObject.parseObject(result.getJSONObject("data").toString(), EditMemberCardBean.class);
                    tv_edit_member_name.setText(cardBean.getName());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                ToastUtils.show(context, "网络错误请稍后再试");
            }
        });
    }


    @OnClick({R.id.iv_back, R.id.tv_edit, R.id.tv_edit_member_delete,
            R.id.rl_edit_member_num,R.id.rl_edit_member_name,R.id.rl_edit_member_mobile,R.id.rl_edit_member_scan})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_edit:
                if(StringUtil.isEmpty(tv_edit_member_mobile.getText().toString())&&StringUtil.isEmpty(tv_edit_member_num.getText().toString())){
                    ToastUtils.show(context,"信息不全");
                }else{
                    changeMemberInfo();
                }
                break;
            case R.id.rl_edit_member_num:
                startActivityForResult(new Intent(this,EditMemberActivity2.class).putExtra("type",NUM).putExtra("content",tv_edit_member_num.getText().toString()),NUM);
                break;
            case R.id.rl_edit_member_name:
                startActivityForResult(new Intent(this,EditMemberActivity2.class).putExtra("type",NAME).putExtra("content",tv_edit_member_name.getText().toString()),NAME);
                break;
            case R.id.rl_edit_member_mobile:
                startActivityForResult(new Intent(this,EditMemberActivity2.class).putExtra("type",MOBILE).putExtra("content",tv_edit_member_mobile.getText().toString()),MOBILE);
                break;
            case R.id.tv_edit_member_delete:
                dialog().show();
                break;
            case R.id.rl_edit_member_scan:
                startActivityForResult(new Intent(this,CommonScanActivity.class),NUM);
                break;
        }
    }

    private NormalAlertDialog dialog() {

         dialog = new NormalAlertDialog.Builder(this)
                .setHeight(0.23f)  //屏幕高度*0.23
                .setWidth(0.75f)  //屏幕宽度*0.65
                .setTitleVisible(true)
                .setTitleText("温馨提示")
                .setTitleTextColor(R.color.black_light)
                .setContentText("确定要删除这张会员卡？")
                .setContentTextColor(R.color.black_light)
                .setLeftButtonText("确定")
                .setLeftButtonTextColor(R.color.gray)
                .setRightButtonText("取消")
                .setRightButtonTextColor(R.color.red)
                .setOnclickListener(new DialogOnClickListener() {
                    @Override
                    public void clickLeftButton(View view) {
                        deleteCard();
                    }
                    @Override
                    public void clickRightButton(View view) {
                        dialog.dismiss();
                    }
                })
                .build();
        return dialog;
    }

    private void deleteCard() {
        HttpParams params = new HttpParams();
        JSONObject obj = new JSONObject();
        obj.put("uid", BaseApp.getModel().getId());
        obj.put("type_id", bean.getType_id());
        params.put("json", obj.toString());
        OkGoRequest.post(UrlUtils.VIP_CARD_DELETE, context, "vip_item" , CacheMode.NO_CACHE, params, new LoadingStringCallBack(EditMemberActivity.this,true) {
            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    org.json.JSONObject result = new org.json.JSONObject(s);
                    if(result.getInt("code") == 0){
                        ToastUtils.show(context,result.getString("msg"));
//                        startActivity(new Intent(EditMemberActivity.this,MemberDeatailActivity.class).putExtra("bean",bean));
                        finish();
                    }else {
                        ToastUtils.show(context,result.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                ToastUtils.show(context, "网络错误请稍后再试");
            }
        });
    }

    private void changeMemberInfo() {
        HttpParams params = new HttpParams();
        JSONObject obj = new JSONObject();
        JSONObject obj2 = new JSONObject();
        obj2.put("cardnum",tv_edit_member_num.getText().toString());
        obj2.put("name",tv_edit_member_name.getText().toString());
        obj2.put("mobile",tv_edit_member_mobile.getText().toString());
        obj.put("uid", BaseApp.getModel().getId());
        obj.put("type_id", bean.getType_id());
        obj.put("data", obj2);
        params.put("json", obj.toString());
        OkGoRequest.post(UrlUtils.VIP_CARD_EDIT, context, "vip_item" , CacheMode.NO_CACHE, params, new LoadingStringCallBack(EditMemberActivity.this,true) {
            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    org.json.JSONObject result = new org.json.JSONObject(s);
                    if(result.getInt("code") == 0){
                        ToastUtils.show(context,result.getString("msg"));
//                        startActivity(new Intent(EditMemberActivity.this,MemberDeatailActivity.class).putExtra("bean",bean));
                        finish();
                    }else {
                        ToastUtils.show(context,result.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                ToastUtils.show(context, "网络错误请稍后再试");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(data == null){
            return;
        }
        switch (requestCode){
            case NUM:
                tv_edit_member_num.setText(data.getExtras().getString("result"));

                break;
            case NAME:
                tv_edit_member_name.setText(data.getExtras().getString("result"));
                break;
            case MOBILE:
                tv_edit_member_mobile.setText(data.getExtras().getString("result"));
                break;
        }
    }

    @Override
    public void finish() {
        startActivity(new Intent(EditMemberActivity.this,MemberDeatailActivity.class).putExtra("bean",bean));
        super.finish();
    }
}
